package com.stx.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stx.common.*;
import com.stx.pojo.Judge;
import com.stx.pojo.ParamChangePwd;
import com.stx.service.IJudgeService;
import com.stx.service.JudgeService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.time.LocalDateTime;
import java.util.*;

@CrossOrigin
@RestController
@Tag(name = "管理员相关接口")
@RequestMapping("/judge")

    public class JudgeController {
    @Autowired
    private JudgeService judgeService;
    private final JwtUtils jwtUtils = new JwtUtils();

    private static final Logger logger = LogManager.getLogger(JudgeController.class);

    @Autowired
    private IJudgeService iJudgeService;

    @Value("${excel.path}")
    private String excelPath;

    @Operation(
            summary = "登录",
            description = "管理员登录",
            tags = {"管理员相关接口"}
    )
    @PostMapping("/login")
    public Result login(@RequestBody Judge judge) {
        judge.setJudUsername(new String(Base64.getDecoder().decode(judge.getJudUsername())));
        judge.setJudPassword(new String(Base64.getDecoder().decode(judge.getJudPassword())));
        Judge loginUser = iJudgeService.findByUsername(judge.getJudUsername());
        if (Objects.isNull(loginUser)) {
            return Result.error("输入不能够为空");
        }
        boolean result1 = CheckPassword.checkPassword(judge.getJudPassword(), judge.getJudUsername());
        if (!result1) {
            return Result.error("密码或者用户名格式不正确");
        }
        logger.trace("登录用户信息：" + loginUser);
        boolean result = Bcrypts.checkPw(judge.getJudPassword(), loginUser.getJudPassword());
        if (result) {
            logger.trace("登录成功");
            Map<String, Object> map = new HashMap<>();
            map.put("username", loginUser.getJudUsername());
            map.put("userId", loginUser.getId());
            map.put("nickName", loginUser.getJudName());
            String data = jwtUtils.generateJwt(map);
            loginUser.setToken(data);
            return Result.success(loginUser);
        } else {
            return Result.error("用户名或密码错误");
        }
    }

    @Operation(
            summary = "注册",
            description = "管理员注册",
            tags = {"管理员相关接口"}
    )
    @PostMapping("/register")
    public Result register(@RequestBody Judge judge) {
        iJudgeService.save(judge);
        return Result.success();
    }

    @Operation(
            summary = "列表",
            description = "管理员列表",
            tags = {"管理员相关接口"}
    )
    @GetMapping("/list")
    public Result getJudges() {
        iJudgeService.getBaseMapper().selectPage(new Page<>(1,100),null);
        List<Judge> list = iJudgeService.list();
        list.get(0).setTotal(list.size());
        return Result.success(list);

    }

    @Operation(
            summary = "添加/修改接口",
            description = "管理员添加和修改列表",
            tags = {"管理员相关接口"}
    )
    @PostMapping("/save")
    public Result save(@Valid@RequestBody Judge judge) {
        /*judge.setJudUsername(new String(Base64.getDecoder().decode(judge.getJudUsername())));
        judge.setJudPassword(new String(Base64.getDecoder().decode(judge.getJudPassword())));
        System.out.println(judge);*/
        boolean result = CheckPassword.checkPassword(judge.getJudPassword(), judge.getJudUsername());
        if (!result) {
            return Result.error("密码或者用户名格式不正确");
        }
        String hashpw = Bcrypts.hashPw(judge.getJudPassword());
        judge.setJudPassword(hashpw);
        judge.setJudDate(LocalDateTime.now());
        iJudgeService.saveOrUpdate(judge);
        return Result.success();
    }

    @Operation(
            summary = "删除接口",
            description = "管理员删除接口，根据id删除",
            tags = {"管理员相关接口"}
    )
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        iJudgeService.removeById(id);
        return Result.success();
    }

    /*@Operation(
            summary = "搜索接口",
            description = "管理员搜索接口",
            tags = {"管理员相关接口"}
    )
    @GetMapping("/search")
    public Result findBySearch(@RequestBody Params params){
        List<Judge> list = judgeService.findBySearch(params);
        return Result.success(list);
    }*/
    @Operation(
            summary = "分页查询用户表",
            description = "分页查询用户表(用户名/姓名)",
            tags = {"管理员相关接口"}
    )
    @PostMapping("/page")
    public Result findPage(@Validated @RequestBody PageValue pageValue) {
        if (pageValue.getCurrentPage() != null && pageValue.getPageSize() != null) {
            Page<Judge> page = judgeService.find(pageValue.getUserName(), pageValue.getJudRole(), pageValue.getCurrentPage(), pageValue.getPageSize());
            return Result.success(page);
        } else {
            List<Judge> list = iJudgeService.list();
            return Result.success(list);
        }
    }

    @Operation(
            summary = "上传excel文件接口",
            description = "上传excel文件接口",
            tags = {"管理员相关接口"}
    )
    @PostMapping("/excel")
    public Result uploadExcel(@RequestParam("file") MultipartFile file, @RequestParam("overwrite") boolean overwrite) {
        try {
            if (file.isEmpty()) {
                return Result.error("File is empty");
            }
            //建立文件夹
            File fileExcel = new File(excelPath);
            if (!fileExcel.exists()) {
                fileExcel.mkdirs();
            }
            // 文件处理成功
            String fileName = file.getOriginalFilename();
            System.out.println(fileName);
            String substring = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
            //File.separator用来代替\\提高文件的跨平台可用
            String fileAddress = fileExcel + File.separator + substring;
            file.transferTo(new File(fileAddress));
            logger.info("文件位置：" + fileAddress);
            EasyExcel.read(fileAddress, Judge.class, new PageReadListener<Judge>(judgeList -> {
                if (overwrite) {
                    logger.info("覆盖");
                    for (Judge judge : judgeList) {
                        List<Judge> byName = iJudgeService.findByName(judge);
                        if (byName.size() != 0) {
                            judge.setId(byName.get(0).getId());
                            iJudgeService.removeBatchByIds(byName);
                            judge.setJudPassword(Bcrypts.hashPw(judge.getJudPassword()));
                            judge.setJudState(1);
                            judge.setJudDate(LocalDateTime.now());
                            //iJudgeService.save(judge);
                        } else {
                            judge.setJudDate(LocalDateTime.now());
                            judge.setJudState(1);
                            judge.setJudPassword(Bcrypts.hashPw(judge.getJudPassword()));
                            //iJudgeService.save(judge);
                        }
                    }
                    iJudgeService.saveBatch(judgeList);
                } else {
                    System.out.println("不覆盖");
                    for (Judge judge : judgeList) {
                        judge.setJudDate(LocalDateTime.now());
                        judge.setJudState(1);
                        judge.setJudPassword(Bcrypts.hashPw(judge.getJudPassword()));
                    }
                    iJudgeService.saveBatch(judgeList);
                }
            })).sheet().doRead();
            return Result.success("File uploaded successfully" + HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("File upload failed" + HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Operation(summary = "修改密码",
            description = "修改密码",
            tags = {"管理员相关接口"})
    @PostMapping("/changePassword")
    public Result changePassword(@RequestBody ParamChangePwd pcp) {
        // 先解密
        pcp.setAccount(new String(Base64.getDecoder().decode(pcp.getAccount())));
        pcp.setOldPassword(new String(Base64.getDecoder().decode(pcp.getOldPassword())));
        pcp.setNewPassword(new String(Base64.getDecoder().decode(pcp.getNewPassword())));
        // 检查新密码的格式
        boolean result = CheckPassword.checkPassword(pcp.getNewPassword(), pcp.getAccount());
        if (!result) {
            return Result.error("密码格式不正确");
        }
        //执行业务
        return judgeService.changePassword(pcp);
    }
}





